import router from "@/router";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { useUserStore } from "@/store/modules/user";

NProgress.configure({ showSpinner: false });

router.beforeEach(async (to, from, next) => {
  NProgress.start();

  const userStore = useUserStore();
  const hasToken = userStore.token;

  if (hasToken) {
    if (to.name === "Login") {
      next("/");
      NProgress.done();
    } else {
      // console.log("userStore.user--", userStore.user);
      // console.log("to--", to);
      if (userStore.user.name) {
        next();
        if (to.path != "/home" && to.path != "/" && userStore.user?.userName) {
          nextTick(() => {
            if (!userStore.user?.isOperate) {
              localStorage.setItem(
                "operaLastPage",
                `${userStore.user.userName}~${to.path}`
              );
            } else {
              localStorage.setItem(
                "yyLastPage",
                `${userStore.user.userName}~${to.path}`
              );
            }
          });
        }
      } else {
        await userStore.getUser();
        next();
        NProgress.done();
        if (to.path != "/home" && to.path != "/" && userStore.user.userName) {
          nextTick(() => {
            if (!userStore.user?.isOperate) {
              localStorage.setItem(
                "operaLastPage",
                `${userStore.user.userName}~${to.path}`
              );
            } else {
              localStorage.setItem(
                "yyLastPage",
                `${userStore.user.userName}~${to.path}`
              );
            }
          });
        }
      }
    }
  } else {
    if (to.name !== "Login") {
      next("/login");
      NProgress.done();
    } else {
      next();
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
